package library.Service;

import library.doMain.Vo.RoleVo;
import library.doMain.Vo.Result;
import library.doMain.dto.RoleDto;
import library.doMain.entry.Role;

import java.util.Arrays;

public class RoleService {
    public static int DATA_SIZE=100;

    public static Role[] data=new Role[DATA_SIZE+1];

    public static int idCounter=1;

    public static RoleVo convertToVo(Role role) {
        return new RoleVo(role.id,role.name,role.dataScope);
    }

    public static Role createEntry(RoleDto dto,int id){
        Role role=new Role(dto.name,dto.dataScope);
        role.id=idCounter++;
        return role;
    }

    public static void updateEntry(RoleDto dto,Role role){
        role.name=dto.name;
        role.dataScope=dto.dataScope;
    }
    public static boolean existsById(int id){
        return id < 1 || id >= idCounter || data[id] == null;
    }
    public static Result list(){
        RoleVo[] temp=new RoleVo[DATA_SIZE];
        int length=0;
        for(int i=0;i<idCounter;i++){
            if(data[i]!=null){
                temp[length++]=convertToVo(data[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp,length));
    }
    public static Result create(RoleDto dto){
        if(idCounter>DATA_SIZE){
            return Result.faliure("创建失败，超出了存储容量");
        }
        Role role=createEntry(dto,idCounter++);
        data[role.id]=role;
        return Result.success("创建成功",null);
    }
    public static Result update(RoleDto dto,int id){
        if(existsById(id)){
            return Result.faliure("更新失败，不存在该数据");
        }
        Role role=data[id];
        updateEntry(dto,role);
        return Result.success("更新成功",null);
    }

    public static Result delete(int id){
        if(existsById(id)){
            return Result.faliure("删除失败，不存在该数据");
        }
        data[id]=null;
        return Result .success("删除成功",null);

    }
}
